/*
 * Copyright(C) 2019 FUYUN DATA SERVICES CO.,LTD. - All Rights Reserved
 * Unauthorized copying of this file, via any medium is strictly prohibited
 * Proprietary and confidential
 * 该源代码版权归属福韵数据服务有限公司所有
 * 未经授权，任何人不得复制、泄露、转载、使用，否则将视为侵权
 *
 */

import * as React from "react";
import { connect } from "react-redux";
import { IRootState, Dispatch } from "../../../../store";
import {
  Form,
  Table,
  Input,
  Button,
  Modal,
  Select,
  DatePicker,
  InputNumber,
  Divider,
  Popconfirm,
  message
} from "antd";

import { FormComponentProps } from "antd/lib/form";
import TitleCard from "src/components/TitleCard";
import TextArea from "antd/lib/input/TextArea";
import moment from "moment";
import locale from "antd/lib/date-picker/locale/zh_CN";

const mapStateToProps = ({
  goods,
  product,
  searchLog,
  loading
}: IRootState) => ({
  goods,
  product,
  searchLog,
  loading: loading.effects.goods.getGoodsList as any
});
const mapDispatchToProps = ({ goods, product, searchLog }: Dispatch) => ({
  getGoodsList: (payload: any) => goods.getGoodsList(payload),
  getGoodsById: (payload: any) => goods.getGoodsById(payload),
  getProductList: (payload: any) => product.getProductList(payload),
  editGoods: (payload: any) => goods.editGoods(payload),
  deleteGoods: (id: string) => goods.deleteGoods(id),
  getBatchAndName: (payload: any) => searchLog.getBatchAndName(payload)
});

type connectedProps = ReturnType<typeof mapStateToProps> &
  ReturnType<typeof mapDispatchToProps>;

interface IState {
  visible: boolean;
  edit: boolean;
  searchValue: string;
  currPage: number;
  selectValue: string;
  selectTime: number;
  children: any;
}

interface IProps extends connectedProps {
  loading: boolean;
}

class GoodsEdit extends React.Component<IProps & FormComponentProps, IState> {
  public state = {
    visible: false,
    edit: true,
    searchValue: "",
    currPage: 0,
    selectValue: "",
    selectTime: 0,
    children: []
  };

  public componentDidMount = async () => {
    const { getGoodsList, getProductList } = this.props;

    await getGoodsList({
      size: "10",
      name: ""
    });

    await getProductList({
      size: "10000",
      name: ""
    });

    const { productList } = this.props.product;
    const cArray: any = [];
    productList.map(v => {
      cArray.push(<Select.Option key={v.id}>{v.name}</Select.Option>);
    });
    this.setState({
      children: cArray
    });
  };

  public handleSearch = () => {
    const { getGoodsList } = this.props;
    getGoodsList({
      name: this.state.searchValue
    });
  };

  public handleOk = (e: any) => {
    const { editGoods } = this.props;
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        editGoods(values);
        this.setState({
          visible: false
        });
      }
    });
  };

  public handleCancel = () => {
    this.setState({
      visible: false
    });
  };

  public handleDetail = async (value: any) => {
    const { getGoodsById } = this.props;
    await getGoodsById(value);

    this.setState({
      visible: true
    });
  };

  public inputChange = (value: any) => {
    this.setState({
      searchValue: value.target.value
    });
  };

  public changePage(pageNumber: any, pageSize: any, props: any) {
    const { getGoodsList } = this.props;
    const payload = {
      name: this.state.searchValue,
      page: pageNumber - 1,
      size: pageSize
    };
    this.setState({
      currPage: pageNumber
    });

    getGoodsList(payload);
  }

  public async deleteHandle(
    id: string,
    goodsBatch?: string,
    goodsName?: string
  ) {
    const { deleteGoods, getBatchAndName } = this.props;
    const objValue = { batch: goodsBatch, name: goodsName };
    await getBatchAndName(objValue);
    const { batchAndNameList } = this.props.searchLog;
    console.log(batchAndNameList);

    if (batchAndNameList.length > 0) {
      message.warning("商品已分配防伪码，请先删除绑定防伪码信息!");
      return;
    }
    deleteGoods(id);
  }

  public tableRender() {
    const { goodsList } = this.props.goods;
    const column = [
      {
        title: "序号",
        dataIndex: "seq",
        render: (text: any, record: any, index: any) => {
          return index + 1;
        }
      },
      {
        title: "产品名称",
        dataIndex: "product"
      },
      {
        title: "商品名称",
        dataIndex: "name"
      },
      {
        title: "商品批次",
        dataIndex: "productBatch"
      },
      {
        title: "产品规格",
        dataIndex: "spec"
      },
      {
        title: "生产时间",
        dataIndex: "productionTime",
        render: (text: any, record: any, index: any) => {
          return (
            <span>
              {text ? moment(text).format("YYYY-MM-DD HH:mm:ss") : " - -"}
            </span>
          );
        }
      },
      {
        title: "操作",
        dataIndex: "",
        render: (text: any, record: any, index: any) => {
          return (
            <div>
              <Button
                type="primary"
                size="small"
                onClick={() => this.handleDetail(record.id)}
              >
                编辑
              </Button>
              <Divider type="vertical" />
              <Popconfirm
                title="确定要删除商品吗？"
                onConfirm={() =>
                  this.deleteHandle(record.id, record.productBatch, record.name)
                }
                okText="确定"
                cancelText="取消"
              >
                <Button type="danger" size="small">
                  删除
                </Button>
              </Popconfirm>
            </div>
          );
        }
      }
    ];

    return (
      <Table
        dataSource={goodsList}
        columns={column}
        rowKey={"id"}
        pagination={{
          current: this.state.currPage,
          total: this.props.goods.pageTotal,
          onChange: (page, size) => this.changePage(page, size, this.props)
        }}
      />
    );
  }

  public handleChange = (value: any, option: any) => {
    const text = option.props.children;
    this.setState({
      selectValue: text
    });
  };

  public timeChange = (date: any, dateString: any) => {
    const res = moment(dateString, "YYYY-MM-DD HH:mm:ss").valueOf();
    this.setState({
      selectTime: res
    });
  };

  public render() {
    const { getFieldDecorator } = this.props.form;
    const { goodsById } = this.props.goods;
    return (
      <div className="message-container" style={{ paddingTop: 32 }}>
        <div style={{ marginLeft: "20px" }}>
          <b>商品名称:</b>
          <Input
            style={{ width: "200px", marginLeft: "10px" }}
            onChange={this.inputChange}
          />
          <Button
            type="primary"
            onClick={this.handleSearch}
            style={{ marginLeft: "10px" }}
          >
            查询
          </Button>
        </div>

        <TitleCard style={{ paddingTop: 32 }}>{this.tableRender()}</TitleCard>

        <Modal
          title={"查看产品"}
          destroyOnClose={true}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
          okText={"确定"}
          cancelText={"取消"}
          visible={this.state.visible}
        >
          <Form>
            <Form.Item
              label={"主键id"}
              labelCol={{ span: 6 }}
              wrapperCol={{ span: 15 }}
              style={{ display: "none" }}
            >
              {getFieldDecorator("id", {
                initialValue: goodsById !== null ? goodsById.id : "",
                rules: [
                  {
                    required: true,
                    message: "主键id"
                  }
                ]
              })(<Input />)}
            </Form.Item>
            <Form.Item
              label={"产品名称"}
              labelCol={{ span: 6 }}
              wrapperCol={{ span: 15 }}
            >
              {getFieldDecorator("proId", {
                initialValue: goodsById !== null ? goodsById.proId : "",
                rules: [
                  {
                    required: true,
                    message: "请选择产品"
                  }
                ]
              })(
                <Select
                  size="default"
                  placeholder="请选择产品"
                  onChange={this.handleChange}
                  style={{ width: "100%" }}
                >
                  {this.state.children}
                </Select>
              )}
            </Form.Item>

            <Form.Item
              label={"产品名称"}
              labelCol={{ span: 6 }}
              wrapperCol={{ span: 15 }}
              style={{ display: "none" }}
            >
              {getFieldDecorator("product", {
                initialValue:
                  this.state.selectValue === ""
                    ? goodsById !== null
                      ? goodsById.product
                      : ""
                    : this.state.selectValue,
                rules: [
                  {
                    required: true,
                    message: "产品id"
                  }
                ]
              })(<Input />)}
            </Form.Item>
            <Form.Item
              label={"商品名称"}
              labelCol={{ span: 6 }}
              wrapperCol={{ span: 15 }}
            >
              {getFieldDecorator("name", {
                initialValue: goodsById !== null ? goodsById.name : "",
                rules: [
                  {
                    required: true,
                    message: "请填写商品名称"
                  }
                ]
              })(<Input />)}
            </Form.Item>

            <Form.Item
              label={"商品批次"}
              labelCol={{ span: 6 }}
              wrapperCol={{ span: 15 }}
            >
              {getFieldDecorator("productBatch", {
                initialValue: goodsById !== null ? goodsById.productBatch : "",
                rules: [
                  {
                    required: true,
                    message: "请填写商品批次"
                  }
                ]
              })(<InputNumber min={0} style={{ width: "100%" }} />)}
            </Form.Item>
            <Form.Item
              label={"生产时间"}
              labelCol={{ span: 6 }}
              wrapperCol={{ span: 15 }}
            >
              {getFieldDecorator("tempTime", {
                initialValue:
                  goodsById !== null
                    ? moment(
                        moment(goodsById.productionTime).format("YYYY-MM-DD"),
                        "yyyy-MM-dd"
                      )
                    : null,
                rules: [
                  {
                    required: true,
                    message: "请选择生产时间"
                  }
                ]
              })(
                <DatePicker
                  placeholder="请选择生产时间"
                  onChange={this.timeChange}
                  locale={locale}
                />
              )}
            </Form.Item>

            <Form.Item
              label={"生产时间"}
              labelCol={{ span: 6 }}
              wrapperCol={{ span: 15 }}
              style={{ display: "none" }}
            >
              {getFieldDecorator("productionTime", {
                initialValue:
                  this.state.selectTime === 0
                    ? goodsById !== null
                      ? goodsById.productionTime
                      : ""
                    : this.state.selectTime,
                rules: [
                  {
                    required: true,
                    message: "请选择生产时间"
                  }
                ]
              })(<Input />)}
            </Form.Item>
            <Form.Item
              label={"产品规格"}
              labelCol={{ span: 6 }}
              wrapperCol={{ span: 15 }}
            >
              {getFieldDecorator("spec", {
                initialValue: goodsById !== null ? goodsById.spec : "",
                rules: [
                  {
                    required: true,
                    message: "请填写产品规格"
                  }
                ]
              })(<TextArea rows={10} cols={10} />)}
            </Form.Item>
          </Form>
        </Modal>
      </div>
    );
  }
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Form.create<IProps & FormComponentProps>({})(GoodsEdit));
